package com.tyk.bookstore.front.payment.strategy.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.tyk.bookstore.front.common.core.model.exception.CustomException;
import com.tyk.bookstore.front.payment.model.result.PaymentResultEnum;
import com.tyk.bookstore.front.payment.strategy.PayAction;
import com.tyk.bookstore.front.payment.strategy.query.PayQuery;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author tyk
 * @description AliPayAction
 */
@Component
@RequiredArgsConstructor
public class AliPayAction implements PayAction<PayQuery> {


    @Value("${mine.pay.ali.return-url}")
    private String returnUrl;

    private final Config config;

    @Override
    public String pay(PayQuery query) {
        Factory.setOptions(config);
        try {
            // 支付宝验签
            AlipayTradePagePayResponse resp = Factory.Payment.Page()
                    .pay(
                            query.getSubject(),
                            String.valueOf(query.getTradNo()),
                            String.valueOf(query.getAmount()),
                            this.returnUrl + query.getTradNo()
                    );
            // 检查是否验签通过
            if (!ResponseChecker.success(resp)) throw new CustomException(PaymentResultEnum.PAY_FAILED);
            // 返回参数
            return resp.body;
        } catch (Exception e) {
            throw new CustomException(PaymentResultEnum.PAY_FAILED);
        }
    }

    @Override
    public void callback(Runnable runnable) {
        runnable.run();
    }
}
